#!/usr/bin/env python 
# -*- coding:utf-8 -*-

import sys
import os
import getopt
from Ump.common.daemon import Daemon
from Ump.websocket import ws_server 
from Ump import defs


class WebsocketDaemon(Daemon):
    def __init__(self):
        self.pidfile = defs.WEB_SOCKET_PID_FILE
        self.name = 'websocket_server'
        self.prog_name = 'websocket_server'
        super(WebsocketDaemon, self).__init__(self.pidfile, name=self.name, prog_name=self.prog_name)


    def run(self):
        ws_server.main()

def usage():
    print ("usage:")
    name = 'ump-websocket-server'
    print (name + " --start")
    print (name + " --stop")
    print (name + " --status")
    print (name + " --test")
    print (name)
    exit(1)

def main():
    op = ''
    ext = None
    try:
        opts, args = getopt.getopt(
                sys.argv[1:],
            'h', ['start', 'stop', 'help', 'test','status']
                )
        if not opts:
            usage()
    except getopt.GetoptError, err:
        usage()

    websocket_daemon = WebsocketDaemon()
    for o, a in opts:
        if o in ('--help'):
            usage()
            exit(0)
        elif (o == '--start'):
            op = o
            websocket_daemon.start()
            print ('%s is running' %(websocket_daemon.name))
        elif (o == '--stop'):
            op = o
            res = websocket_daemon.stop()
            if res:
                print ('%s is stopped' % (websocket_daemon.name))
        elif (o == '--test'):
            websocket_daemon.run()
        elif (o == '--status'):
            is_run,pid = websocket_daemon.status()
            if is_run:
                print ('%s is running,pid is %s' %(websocket_daemon.name,pid))
            else:
                print ('%s is stopped' % (websocket_daemon.name))
        else:
            assert False, 'oops, unhandled option: %s, -h for help' % o
            exit(1)

if __name__ == '__main__':
    if (len(sys.argv) == 1):
        usage()
    else:
        main()

